// let targetUrl = 'https://www.dytt8.net/html/gndy/dyzz/list_23_1.html'

// let axios = require('axios')

let request = require('request')
let fs = require('fs')
let {fsWrite,fsRead,fsDir} = require('./fs')
let httpUrl = 'https://www.1905.com/vod/list/n_1/o3u1p1.html?fr=vodhome_js_lx'

//获取起始页面的所有分类
// 获取分类的电影
//根据电影连接获取电影详情信息



function req(url) {
    return new Promise(function (resolve,reject) {
        request.get(url,function(err,response,body){
            if(err){
                reject(err)
            }else{
                resolve({response,body})
            }
        })
     })
 }

//分类地址
async function getClassUrl() {
    let {response,body} = await req(httpUrl)
    // console.log(body)
    let reg = /<span class="search-index-L">类型(.*?)<div class="grid-12x">/igs
    //解析html内容
    let result = reg.exec(body)[1]
    let reg1 = /<a href="javascript\:void\(0\);" onclick="location\.href='(.*?)';return false;".*?>(.*?)<\/a>/igs
    let arrClass = []
    var res;
    while(res = reg1.exec(result)){
        if(res[2] != "全部"){
            let obj = {
                className:res[2],
                url:res[1]
            }
            arrClass.push(obj)
            await fsDir('./movies/'+res[2])
            getMovie(res[1],res[2])
        }
    }
 }



 //通过分类，获取页面中的电影链接
 async function getMovie(url,MovieType) {
     let {response,body} = await req(url)
     let reg = /<a class="pic-pack-outer" target="_blank" href="(.*?)".*?><img/igs
     var res;
     var arrList = []
     while(res = reg.exec(body)){

         arrList.push(res[1])
         parsePage(res[1],MovieType)
     }
    //  console.log("分类：",MovieType)
    //  console.log(arrList)
  }



async function parsePage(url,MovieType) {
    let {response,body} = await req(url)
    let reg = /<h1 class="playerBox-info-name playerBox-info-cnName">(.*?)<\/h1>.*?<span class="playerBox-info-year">\((.*?)\)<\/span>.*?id="playerBoxIntroCon">(.*?)<a.*?导演.*?target="\_blank" title="(.*?)" data-hrefexp.*?地区<b>.*?target="\_blank" title="(.*?)" data-hrefexp/igs
    let res= reg.exec(body)
    console.log(res[1])
    let movie = {
        name:res[1],
        year:res[2],
        brief:res[3],
        daoyan:res[4],
        diqu:res[5],
        movieUrl:url,
        MovieType
    }
    let strMovie = JSON.stringify(movie)
    fsWrite('./movies/'+MovieType+"/"+res[1]+".json",strMovie)


}


 getClassUrl()